# -*- coding: utf-8 -*-
import requests #type: ignore
from config import AUDIO_ROOT
from iamtoken import get_token
import json
import base64
import subprocess  # 导入subprocess模块
import sys  # 导入 sys 模块以访问命令行参数
import playaudio

url = "https://sis-ext.cn-north-4.myhuaweicloud.com/v1/7703c099b8f5485985140d72ce89715a/tts"
def main(text):
    payload = {
    "text":text,
    "config": {
    "audio_format": "wav",
    "sample_rate": "16000",
    "property": "chinese_huaxiaofei_common"
    }
    }
    headers = {
        'Content-Type': 'application/json',
        'X-Auth-Token': get_token()
    }


    response = requests.request("POST", url, headers=headers, data=json.dumps(payload))

    audiostr = json.loads(response.text).get("result").get("data")
    print(f"audio str: {audiostr[0:10]}")

    audio_data = base64.b64decode(audiostr)

    with open("tts.wav", "wb") as f:
        f.write(audio_data)  # 写入解码后的字节数据

    # 如果没有提供音频文件路径，则按照原来的流程处理
    # 先将 test.wav 转换为采样率 48000 Hz，单声道，音量 0.1，并输出为 s16le PCM 数据
    subprocess.run([
        "ffmpeg",
        "-loglevel", "quiet", 
        "-i", "tts.wav",            # 让 ffmpeg 自动识别输入文件格式（wav）
        "-ar", "48000",              # 输出音频采样率 48000 Hz
        "-ac", "1",                  # 输出单声道音频
        "-filter:a", "volume=0.1",   # 将音量设置为原来的 10%
        "-f", "s16le",               # 指定输出格式为 s16le（原始 PCM）
        "-y",                        # 如果文件已存在则自动覆盖
        "tts.pcm"
    ])
    playaudio.main("tts.pcm")

if __name__ == "__main__":
    speech = sys.argv[1] if len(sys.argv) > 1 else "你好,我是香橙派"
    main(speech)